<template>
  <div class="approval-management">
    <!-- 主页面 -->
    <div class="main-content">
      <div class="header">
        <h2>审批管理</h2>
        <div class="header-actions">
          <el-button type="primary" @click="showProcessDialog">流程管理</el-button>
          <el-button type="success" @click="showTodoDialog">待办审批</el-button>
          <el-button type="info" @click="showHistoryDialog">审批历史</el-button>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="statistics">
        <div class="statistics-header">
          <h3>审批统计</h3>
          <el-button type="primary" size="small" @click="refreshStatistics" :loading="statisticsLoading">
            <el-icon>
              <Refresh />
            </el-icon>
            刷新统计
          </el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ statistics.totalProcesses }}</div>
                <div class="stat-label">审批流程</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ statistics.pendingTodos }}</div>
                <div class="stat-label">待办审批</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ statistics.processingTodos }}</div>
                <div class="stat-label">审批中</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ statistics.completedTodos }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 最近审批列表 -->
      <div class="recent-approvals">
        <h3>最近审批</h3>
        <el-table :data="recentApprovals" v-loading="loading" border>
          <el-table-column prop="businessType" label="业务类型" width="120" />
          <el-table-column prop="businessName" label="业务名称" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="initiatorName" label="发起人" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewDetail(row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 审批流程管理对话框 -->
    <el-dialog v-model="processDialogVisible" title="审批流程管理" width="90%" :close-on-click-modal="false">
      <div class="approval-process-content">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-form :model="processSearchForm" inline>
            <el-form-item label="流程名称">
              <el-input v-model="processSearchForm.processName" placeholder="请输入流程名称" clearable />
            </el-form-item>
            <el-form-item label="表单类型" style="width: 200px;">
              <el-select v-model="processSearchForm.formType" placeholder="请选择表单类型" clearable>
                <el-option label="采购申请" value="采购申请" />
                <el-option label="请假申请" value="请假申请" />
                <el-option label="报销申请" value="报销申请" />
                <el-option label="合同审批" value="合同审批" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" style="width: 200px;">
              <el-select v-model="processSearchForm.isEnabled" placeholder="请选择状态" clearable>
                <el-option label="启用" :value="true" />
                <el-option label="禁用" :value="false" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchProcesses">搜索</el-button>
              <el-button @click="resetProcessSearch">重置</el-button>
              <el-button type="success" @click="showCreateProcessDialog">新建流程</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 流程列表 -->
        <el-table :data="processList" v-loading="processLoading" border>
          <el-table-column prop="processName" label="流程名称" width="270" />
          <el-table-column prop="formType" label="表单类型" width="200" />
          <el-table-column prop="description" label="描述" width="405" />
          <el-table-column prop="isEnabled" label="状态" width="200">
            <template #default="{ row }">
              <el-switch v-model="row.isEnabled" @change="toggleProcessStatus(row)" />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="250">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="600" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewProcessNodes(row)">查看节点</el-button>
              <el-button type="warning" size="small" @click="editProcess(row)">编辑</el-button>
              <el-button type="success" size="small" @click="showCreateInstanceDialog(row)">创建实例</el-button>
              <el-button type="danger" size="small" @click="deleteProcess(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination v-model:current-page="processPagination.pageIndex"
            v-model:page-size="processPagination.pageSize" :page-sizes="[10, 20, 50, 100]"
            :total="processPagination.total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleProcessSizeChange" @current-change="handleProcessCurrentChange" />
        </div>
      </div>
    </el-dialog>

    <!-- 创建审批流程对话框 -->
    <el-dialog v-model="createProcessDialogVisible" title="创建审批流程" width="1200px" :close-on-click-modal="false">
      <el-form :model="createProcessForm" :rules="createProcessRules" ref="createProcessFormRef" label-width="120px">
        <el-form-item label="流程名称" prop="processName">
          <el-input v-model="createProcessForm.processName" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="表单类型" prop="formType" style="width: 300px;">
          <el-select v-model="createProcessForm.formType" placeholder="请选择表单类型" style="width: 100%">
            <el-option label="采购申请" value="采购申请" />
            <el-option label="请假申请" value="请假申请" />
            <el-option label="报销申请" value="报销申请" />
            <el-option label="合同审批" value="合同审批" />
          </el-select>
        </el-form-item>
        <el-form-item label="流程描述" prop="description">
          <el-input v-model="createProcessForm.description" type="textarea" :rows="3" placeholder="请输入流程描述" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="createProcessForm.isEnabled" />
        </el-form-item>

        <el-divider content-position="left">审批节点</el-divider>

        <div v-for="(node, index) in createProcessForm.nodes" :key="index" class="node-item"
          style="margin-bottom: 20px; padding: 20px; border: 1px solid #e4e7ed; border-radius: 6px; background-color: #fafafa;">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item :label="`节点${index + 1}`" :prop="`nodes.${index}.nodeName`"
                :rules="{ required: true, message: '请输入节点名称', trigger: 'blur' }">
                <el-input v-model="node.nodeName" placeholder="请输入节点名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`审批人`" :prop="`nodes.${index}.approverName`"
                :rules="{ required: true, message: '请选择审批人', trigger: 'change' }">
                <el-select v-model="node.approverName" placeholder="请选择审批人" style="width: 100%"
                  v-loading="userListLoading">
                  <el-option v-for="(user, userIndex) in userList" :key="user?.id || userIndex"
                    :label="user?.name || '未知用户'" :value="(user?.id || '').toString()" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="`排序`" :prop="`nodes.${index}.orderIndex`"
                :rules="{ required: true, message: '请输入排序', trigger: 'blur' }">
                <el-input-number v-model="node.orderIndex" :min="1" :max="10" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-form-item label=" ">
                <el-button type="danger" size="small" @click="removeNode(index)"
                  :disabled="createProcessForm.nodes.length <= 1">删除</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-form-item>
          <el-button type="primary" @click="addNode">添加节点</el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createProcessDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreateProcess" :loading="createProcessLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看流程节点对话框 -->
    <el-dialog v-model="viewNodesDialogVisible" title="查看流程节点" width="800px" :close-on-click-modal="false">
      <div v-if="currentProcess" class="process-nodes-content">
        <div class="process-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="流程名称">{{ currentProcess.processName }}</el-descriptions-item>
            <el-descriptions-item label="表单类型">{{ currentProcess.formType }}</el-descriptions-item>
            <el-descriptions-item label="流程描述">{{ currentProcess.description || '无' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="currentProcess.isEnabled ? 'success' : 'danger'">
                {{ currentProcess.isEnabled ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <el-divider content-position="left">审批节点</el-divider>

        <el-table :data="currentProcessNodes" border>
          <el-table-column prop="orderIndex" label="排序" width="80" />
          <el-table-column prop="nodeName" label="节点名称" />
          <el-table-column prop="approverName" label="审批人">
            <template #default="{ row }">
              {{ getUserNameById(row.approverName) }}
            </template>
          </el-table-column>
          <el-table-column prop="isRequired" label="是否必填" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isRequired ? 'success' : 'info'">
                {{ row.isRequired ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 当没有节点数据时显示提示 -->
        <div v-if="!currentProcessNodes || currentProcessNodes.length === 0"
          style="text-align: center; padding: 40px; color: #909399;">
          <el-icon size="48" style="margin-bottom: 16px;">
            <InfoFilled />
          </el-icon>
          <p>该流程暂无审批节点</p>
          <p style="font-size: 14px; margin-top: 8px;">请点击"编辑"按钮为该流程添加审批节点</p>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑流程对话框 -->
    <el-dialog v-model="editProcessDialogVisible" title="编辑审批流程" width="1200px" :close-on-click-modal="false">
      <el-form :model="editProcessForm" :rules="editProcessRules" ref="editProcessFormRef" label-width="120px">
        <el-form-item label="流程名称" prop="processName">
          <el-input v-model="editProcessForm.processName" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="表单类型" prop="formType" style="width: 200px;">
          <el-select v-model="editProcessForm.formType" placeholder="请选择表单类型" style="width: 100%">
            <el-option label="采购申请" value="采购申请" />
            <el-option label="请假申请" value="请假申请" />
            <el-option label="报销申请" value="报销申请" />
            <el-option label="合同审批" value="合同审批" />
          </el-select>
        </el-form-item>
        <el-form-item label="流程描述" prop="description">
          <el-input v-model="editProcessForm.description" type="textarea" :rows="3" placeholder="请输入流程描述" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="editProcessForm.isEnabled" />
        </el-form-item>

        <el-divider content-position="left">审批节点</el-divider>

        <div v-for="(node, index) in editProcessForm.nodes" :key="index" class="node-item"
          style="margin-bottom: 20px; padding: 20px; border: 1px solid #e4e7ed; border-radius: 6px; background-color: #fafafa;">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item :label="`节点${index + 1}`" :prop="`nodes.${index}.nodeName`"
                :rules="{ required: true, message: '请输入节点名称', trigger: 'blur' }">
                <el-input v-model="node.nodeName" placeholder="请输入节点名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`审批人`" :prop="`nodes.${index}.approverName`"
                :rules="{ required: true, message: '请选择审批人', trigger: 'change' }">
                <el-select v-model="node.approverName" placeholder="请选择审批人" style="width: 100%"
                  v-loading="userListLoading">
                  <el-option v-for="(user, userIndex) in userList" :key="user?.id || userIndex"
                    :label="user?.name || '未知用户'" :value="(user?.id || '').toString()" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="`排序`" :prop="`nodes.${index}.orderIndex`"
                :rules="{ required: true, message: '请输入排序', trigger: 'blur' }">
                <el-input-number v-model="node.orderIndex" :min="1" :max="10" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label=" ">
                <el-button type="danger" size="small" @click="removeEditNode(index)"
                  :disabled="editProcessForm.nodes.length <= 1">删除</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-form-item>
          <el-button type="primary" @click="addEditNode">添加节点</el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editProcessDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditProcess" :loading="editProcessLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 待办审批对话框 -->
    <el-dialog v-model="todoDialogVisible" title="待办审批" width="90%" :close-on-click-modal="false">
      <div class="approval-todo-content">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-form :model="todoSearchForm" inline>
            <el-form-item label="业务类型" style="width: 230px;">
              <el-select v-model="todoSearchForm.businessType" placeholder="请选择业务类型" clearable>
                <el-option label="采购申请" value="采购申请" />
                <el-option label="请假申请" value="请假申请" />
                <el-option label="报销申请" value="报销申请" />
                <el-option label="合同审批" value="合同审批" />
              </el-select>
            </el-form-item>
            <el-form-item label="发起人">
              <el-input v-model="todoSearchForm.initiatorName" placeholder="请输入发起人" clearable />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker v-model="todoSearchForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchTodos">搜索</el-button>
              <el-button @click="resetTodoSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 待办列表 -->
        <el-table :data="todoList" v-loading="todoLoading" border>
          <el-table-column prop="businessType" label="业务类型" width="200" />
          <el-table-column prop="businessName" label="业务名称" width="230" />
          <el-table-column prop="businessId" label="业务ID" width="170" />
          <el-table-column prop="initiatorName" label="发起人" width="200" />
          <el-table-column prop="createTime" label="创建时间" width="200">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容" width="450" />
          <el-table-column label="操作" width="400" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewTodoDetail(row)">查看详情</el-button>
              <el-button type="success" size="small" @click="approveTodo(row)">同意</el-button>
              <el-button type="danger" size="small" @click="rejectTodo(row)">拒绝</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination v-model:current-page="todoPagination.pageIndex" v-model:page-size="todoPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="todoPagination.total"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleTodoSizeChange"
            @current-change="handleTodoCurrentChange" />
        </div>
      </div>
    </el-dialog>

    <!-- 审批历史对话框 -->
    <el-dialog v-model="historyDialogVisible" title="审批历史" width="90%" :close-on-click-modal="false">
      <div class="approval-history-content">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-form :model="historySearchForm" inline>
            <el-form-item label="业务类型">
              <el-select v-model="historySearchForm.businessType" style="width: 200px;" placeholder="请选择业务类型" clearable>
                <el-option label="采购申请" value="采购申请" />
                <el-option label="请假申请" value="请假申请" />
                <el-option label="报销申请" value="报销申请" />
                <el-option label="合同审批" value="合同审批" />
              </el-select>
            </el-form-item>
            <el-form-item label="审批状态" style="width: 200px;">
              <el-select v-model="historySearchForm.status" placeholder="请选择状态" clearable>
                <el-option label="已完成" value="completed" />
                <el-option label="已拒绝" value="rejected" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
            <el-form-item label="完成时间">
              <el-date-picker v-model="historySearchForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchHistory">搜索</el-button>
              <el-button @click="resetHistorySearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 历史列表 -->
        <el-table :data="historyList" v-loading="historyLoading" border>
          <el-table-column prop="businessType" label="业务类型" width="120" />
          <el-table-column prop="businessName" label="业务名称" />
          <el-table-column prop="businessId" label="业务ID" width="150" />
          <el-table-column prop="initiatorName" label="发起人" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="completeTime" label="完成时间" width="160">
            <template #default="{ row }">
              {{ row.completeTime ? formatDateTime(row.completeTime) : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewHistoryDetail(row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination v-model:current-page="historyPagination.pageIndex"
            v-model:page-size="historyPagination.pageSize" :page-sizes="[10, 20, 50, 100]"
            :total="historyPagination.total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleHistorySizeChange" @current-change="handleHistoryCurrentChange" />
        </div>
      </div>
    </el-dialog>

    <!-- 创建审批实例对话框 -->
    <el-dialog v-model="createInstanceDialogVisible" title="创建审批实例" width="600px" :close-on-click-modal="false">
      <el-form :model="createInstanceForm" :rules="createInstanceRules" ref="createInstanceFormRef" label-width="120px">
        <el-form-item label="流程名称">
          <el-input v-model="createInstanceForm.processName" disabled />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-input v-model="createInstanceForm.businessType" placeholder="请输入业务类型" />
        </el-form-item>
        <el-form-item label="业务名称" prop="businessName">
          <el-input v-model="createInstanceForm.businessName" placeholder="请输入业务名称" />
        </el-form-item>
        <el-form-item label="业务ID" prop="businessId">
          <el-input v-model="createInstanceForm.businessId" placeholder="请输入业务ID" />
        </el-form-item>
        <el-form-item label="申请内容" prop="content">
          <el-input v-model="createInstanceForm.content" type="textarea" :rows="4" placeholder="请输入申请内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createInstanceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreateInstance" :loading="createInstanceLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审批详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="审批详情" width="800px">
      <div v-if="currentInstance" class="approval-detail">
        <div class="detail-section">
          <h4>基本信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="业务类型">{{ currentInstance.businessType }}</el-descriptions-item>
            <el-descriptions-item label="业务名称">{{ currentInstance.businessName }}</el-descriptions-item>
            <el-descriptions-item label="业务ID">{{ currentInstance.businessId }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(currentInstance.status)">
                {{ getStatusText(currentInstance.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="发起人">{{ currentInstance.initiatorName }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(currentInstance.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="内容" :span="2">{{ currentInstance.content || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h4>审批流程</h4>
          <el-steps :active="currentInstance.currentNodeIndex" direction="vertical">
            <el-step v-for="(record, index) in currentInstance.records" :key="index" :title="record.approverName"
              :description="getStepDescription(record)">
              <template #icon>
                <el-icon v-if="record.result === 'approve' || record.result === 'approved'">
                  <Check />
                </el-icon>
                <el-icon v-else-if="record.result === 'reject' || record.result === 'rejected'">
                  <Close />
                </el-icon>
                <el-icon v-else>
                  <Clock />
                </el-icon>
              </template>
            </el-step>
          </el-steps>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getApprovalInstances,
  getApprovalInstanceById,
  approveReject,
  getApprovalProcesses,
  createApprovalProcess,
  getApprovalProcessById,
  updateApprovalProcess,
  toggleApprovalProcess,
  deleteApprovalProcess,
  createApprovalInstance,
  getAllUsers,
  getMyPendingApprovals
} from '@/Https/server'
import { Check, Close, Clock, InfoFilled, Refresh } from '@element-plus/icons-vue'
// 已删除独立的对话框组件，所有功能集成在主页面中

// 接口定义
interface ApprovalInstance {
  id: number
  approvalProcessId: number
  businessId: string
  businessType: string
  businessName: string
  currentNodeIndex: number
  status: string
  initiatorId: number
  initiatorName: string
  content?: string
  createTime: string
  records: ApprovalRecord[]
}

interface ApprovalRecord {
  id: number
  approvalInstanceId: number
  approvalNodeId: number
  approverId: number
  approverName: string
  result: string
  comment?: string
  approveTime: string
}

// 响应式数据
const loading = ref(false)
const recentApprovals = ref<ApprovalInstance[]>([])
const currentInstance = ref<ApprovalInstance | null>(null)

// 统计数据
const statistics = reactive({
  totalProcesses: 0,
  pendingTodos: 0,
  processingTodos: 0,
  completedTodos: 0
})
const statisticsLoading = ref(false)

// 对话框控制
const processDialogVisible = ref(false)
const todoDialogVisible = ref(false)
const historyDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const createProcessDialogVisible = ref(false)
const viewNodesDialogVisible = ref(false)
const editProcessDialogVisible = ref(false)

// 查看节点相关数据
const currentProcess = ref<any>(null)
const currentProcessNodes = ref<any[]>([])

// 编辑流程相关数据
const editProcessLoading = ref(false)
const editProcessFormRef = ref()
const editProcessForm = reactive({
  id: 0,
  processName: '',
  formType: '',
  description: '',
  isEnabled: true,
  nodes: [
    {
      nodeName: '',
      approverName: '',
      orderIndex: 1,
      isRequired: true
    }
  ]
})

const editProcessRules = {
  processName: [
    { required: true, message: '请输入流程名称', trigger: 'blur' }
  ],
  formType: [
    { required: true, message: '请选择表单类型', trigger: 'change' }
  ]
}

// 创建实例相关数据
const createInstanceDialogVisible = ref(false)
const createInstanceLoading = ref(false)
const createInstanceFormRef = ref()
const createInstanceForm = reactive({
  approvalProcessId: 0,
  processName: '',
  businessType: '',
  businessName: '',
  businessId: '',
  content: ''
})
const createInstanceRules = {
  businessType: [{ required: true, message: '请输入业务类型', trigger: 'blur' }],
  businessName: [{ required: true, message: '请输入业务名称', trigger: 'blur' }],
  businessId: [{ required: true, message: '请输入业务ID', trigger: 'blur' }],
  content: [{ required: true, message: '请输入申请内容', trigger: 'blur' }]
}

// 创建流程相关数据
const createProcessLoading = ref(false)
const createProcessFormRef = ref()
const createProcessForm = reactive({
  processName: '',
  formType: '',
  description: '',
  isEnabled: true,
  nodes: [
    {
      nodeName: '',
      approverName: '',
      orderIndex: 1,
      isRequired: true
    }
  ]
})

const createProcessRules = {
  processName: [
    { required: true, message: '请输入流程名称', trigger: 'blur' }
  ],
  formType: [
    { required: true, message: '请选择表单类型', trigger: 'change' }
  ]
}

// 流程管理相关数据
const processLoading = ref(false)
const processList = ref<any[]>([])
const processSearchForm = reactive({
  processName: '',
  formType: '',
  isEnabled: undefined as boolean | undefined
})
const processPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 待办审批相关数据
const todoLoading = ref(false)
const todoList = ref<ApprovalInstance[]>([])
const todoSearchForm = reactive({
  businessType: '',
  initiatorName: '',
  dateRange: [] as string[]
})
const todoPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 审批历史相关数据
const historyLoading = ref(false)
const historyList = ref<ApprovalInstance[]>([])
const historySearchForm = reactive({
  businessType: '',
  status: '',
  dateRange: [] as string[]
})
const historyPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 用户列表数据
const userList = ref<any[]>([])
const userListLoading = ref(false)

// 方法
const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 加载用户列表
const loadUserList = async () => {
  try {
    userListLoading.value = true
    // 传递必要的参数
    const params = {
      PageIndex: 1,
      PageSize: 100, // 获取足够多的用户
      NickName: '' // 空字符串表示获取所有用户
    }
    console.log('获取用户列表 - 请求参数:', params)
    const result = await getAllUsers(params)
    console.log('获取用户列表 - API返回结果:', result)
    
    if (result && result.data) {
      // 检查数据格式并转换
      let userData = result.data
      if (Array.isArray(userData)) {
        userList.value = userData
      } else if (userData.pageData && Array.isArray(userData.pageData)) {
        userList.value = userData.pageData
      } else {
        userList.value = []
      }
      console.log('处理后的用户列表:', userList.value)
    } else {
      // 如果API调用失败，使用默认用户数据
      userList.value = [
        { id: 1, name: '系统管理员' },
        { id: 2, name: '张三' },
        { id: 3, name: '李四' },
        { id: 4, name: '王五' },
        { id: 5, name: '赵六' },
        { id: 6, name: '钱七' }
      ]
      console.warn('使用默认用户数据')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    // 如果API调用失败，使用默认用户数据
    userList.value = [
      { id: 1, name: '系统管理员' },
      { id: 2, name: '张三' },
      { id: 3, name: '李四' },
      { id: 4, name: '王五' },
      { id: 5, name: '赵六' },
      { id: 6, name: '钱七' }
    ]
    console.warn('使用默认用户数据')
  } finally {
    userListLoading.value = false
  }
}

// 根据用户ID获取用户姓名
const getUserNameById = (userId: string | number) => {
  if (!userId) return '未设置'
  const user = userList.value.find(u => u?.id?.toString() === userId.toString())
  return user?.name || `用户${userId}`
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'processing': return 'primary'
    case 'approved': return 'success'
    case 'completed': return 'success'
    case 'rejected': return 'danger'
    case 'cancelled': return 'info'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待审批'
    case 'processing': return '审批中'
    case 'approved': return '已完成'
    case 'completed': return '已完成'
    case 'rejected': return '已拒绝'
    case 'cancelled': return '已取消'
    default: return '未知'
  }
}

const getStepDescription = (record: ApprovalRecord) => {
  if (record.result === 'approve' || record.result === 'approved') {
    return `同意 - ${record.comment || '无意见'} (${formatDateTime(record.approveTime)})`
  } else if (record.result === 'reject' || record.result === 'rejected') {
    return `拒绝 - ${record.comment || '无意见'} (${formatDateTime(record.approveTime)})`
  } else if (record.result === 'pending') {
    return '待审批'
  } else {
    return '待审批'
  }
}

const loadStatistics = async () => {
  try {
    // 获取审批流程数量
    const processResult: any = await getApprovalProcesses({})
    let totalProcesses = 4 // 默认值
    if (processResult.code === 200 && processResult.data && processResult.data.pageData) {
      totalProcesses = processResult.data.totalCount || 4
    }

    // 获取当前用户的待审批数量
    const pendingResult: any = await getMyPendingApprovals()
    let pendingCount = 0
    if (pendingResult.code === 200 && pendingResult.data) {
      pendingCount = pendingResult.data.length || 0
    }

    // 调用API获取审批实例列表来计算其他统计数据
    const params = {
      pageIndex: '1',
      pageSize: '1000' // 获取更多数据来计算统计
    }

    const result: any = await getApprovalInstances(params)
    if (result.code === 200 && result.data && result.data.pageData) {
      const allInstances = result.data.pageData

      // 计算统计数据
      statistics.totalProcesses = totalProcesses
      // 待办审批：使用当前用户的实际待审批数量
      statistics.pendingTodos = pendingCount
      statistics.processingTodos = allInstances.filter((item: ApprovalInstance) => item.status === 'processing').length
      // 修复：包含所有已完成状态（approved, completed）
      statistics.completedTodos = allInstances.filter((item: ApprovalInstance) =>
        ['approved', 'completed'].includes(item.status)
      ).length

      console.log('统计数据:', statistics)
      console.log('当前用户待审批数量:', pendingCount)
      console.log('所有实例状态:', allInstances.map((item: ApprovalInstance) => ({ id: item.id, status: item.status })))
    } else {
      // 如果API不可用，使用模拟数据
      statistics.totalProcesses = totalProcesses
      statistics.pendingTodos = pendingCount // 使用实际的待审批数量
      statistics.processingTodos = 2
      statistics.completedTodos = 10
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 使用模拟数据
    statistics.totalProcesses = 4
    statistics.pendingTodos = 0 // 出错时设为0
    statistics.processingTodos = 2
    statistics.completedTodos = 10
  }
}

const refreshStatistics = async () => {
  statisticsLoading.value = true
  try {
    await loadStatistics()
    ElMessage.success('统计数据已刷新')
  } catch (error) {
    console.error('刷新统计数据失败:', error)
    ElMessage.error('刷新统计数据失败')
  } finally {
    statisticsLoading.value = false
  }
}

const loadRecentApprovals = async () => {
  loading.value = true
  try {
    const params = {
      pageIndex: '1',
      pageSize: '10'
    }

    const result: any = await getApprovalInstances(params)
    console.log('API返回数据:', result) // 调试日志

    if (result.code === 200 && result.data && result.data.pageData) {
      // 使用API返回的真实数据
      recentApprovals.value = result.data.pageData
      console.log('设置审批数据:', recentApprovals.value)
    } else {
      console.log('API返回格式异常，使用模拟数据')
      // 如果API不可用，显示模拟数据
      recentApprovals.value = getMockData()
    }
  } catch (error) {
    console.error('获取最近审批列表失败:', error)
    // 网络错误时显示模拟数据
    recentApprovals.value = getMockData()
  } finally {
    loading.value = false
  }
}

// 模拟数据
const getMockData = () => {
  return [
    {
      id: 1,
      approvalProcessId: 1,
      businessId: 'PO-2024-001',
      businessType: '采购申请',
      businessName: '原材料采购申请',
      currentNodeIndex: 2,
      status: 'processing',
      initiatorId: 1,
      initiatorName: '张三',
      content: '采购钢材100吨，用于生产车间使用',
      createTime: '2024-08-21T10:30:00',
      records: [
        {
          id: 1,
          approvalInstanceId: 1,
          approvalNodeId: 1,
          approverId: 2,
          approverName: '张经理',
          result: 'approve',
          comment: '同意采购，价格合理',
          approveTime: '2024-08-21T11:00:00'
        }
      ]
    },
    {
      id: 2,
      approvalProcessId: 1,
      businessId: 'WO-2024-002',
      businessType: '工单申请',
      businessName: '生产工单申请',
      currentNodeIndex: 1,
      status: 'pending',
      initiatorId: 2,
      initiatorName: '李四',
      content: '申请生产工单，生产产品A型号100件',
      createTime: '2024-08-21T09:15:00',
      records: []
    },
    {
      id: 3,
      approvalProcessId: 2,
      businessId: 'INV-2024-003',
      businessType: '库存申请',
      businessName: '库存盘点申请',
      currentNodeIndex: 3,
      status: 'completed',
      initiatorId: 3,
      initiatorName: '王五',
      content: '月度库存盘点，检查所有仓库库存情况',
      createTime: '2024-08-20T16:45:00',
      records: [
        {
          id: 2,
          approvalInstanceId: 3,
          approvalNodeId: 3,
          approverId: 4,
          approverName: '王主管',
          result: 'approve',
          comment: '同意盘点，注意安全',
          approveTime: '2024-08-21T09:30:00'
        },
        {
          id: 3,
          approvalInstanceId: 3,
          approvalNodeId: 4,
          approverId: 5,
          approverName: '刘总监',
          result: 'approve',
          comment: '盘点完成，数据准确',
          approveTime: '2024-08-21T14:20:00'
        }
      ]
    },
    {
      id: 4,
      approvalProcessId: 1,
      businessId: 'EQ-2024-004',
      businessType: '设备申请',
      businessName: '设备维护申请',
      currentNodeIndex: 1,
      status: 'pending',
      initiatorId: 4,
      initiatorName: '赵六',
      content: '申请设备维护，更换零件',
      createTime: '2024-08-21T14:30:00',
      records: []
    },
    {
      id: 5,
      approvalProcessId: 2,
      businessId: 'HR-2024-005',
      businessType: '人事申请',
      businessName: '员工请假申请',
      currentNodeIndex: 2,
      status: 'processing',
      initiatorId: 5,
      initiatorName: '钱七',
      content: '申请年假5天，时间：2024-09-01至2024-09-05',
      createTime: '2024-08-21T15:00:00',
      records: [
        {
          id: 4,
          approvalInstanceId: 5,
          approvalNodeId: 5,
          approverId: 6,
          approverName: '孙主管',
          result: 'approve',
          comment: '同意请假申请',
          approveTime: '2024-08-21T16:00:00'
        }
      ]
    },
    // 添加一个已拒绝状态的审批，包含完整的审批记录
    {
      id: 6,
      approvalProcessId: 1,
      businessId: 'LEAVE20240821003',
      businessType: '请假申请',
      businessName: '事假申请',
      currentNodeIndex: 2,
      status: 'rejected',
      initiatorId: 7,
      initiatorName: '销售员小赵',
      content: '申请事假1天, 2024-08-23',
      createTime: '2025-08-22T00:22:16',
      records: [
        {
          id: 5,
          approvalInstanceId: 6,
          approvalNodeId: 1,
          approverId: 8,
          approverName: '部门经理',
          result: 'approve',
          comment: '同意事假申请',
          approveTime: '2025-08-22T10:30:00'
        },
        {
          id: 6,
          approvalInstanceId: 6,
          approvalNodeId: 2,
          approverId: 9,
          approverName: '人事主管',
          result: 'reject',
          comment: '当前工作繁忙，建议延期',
          approveTime: '2025-08-22T14:15:00'
        }
      ]
    }
  ]
}

const showProcessDialog = () => {
  processDialogVisible.value = true
  loadProcesses()
}

const showTodoDialog = () => {
  todoDialogVisible.value = true
  loadTodos()
}

const showHistoryDialog = () => {
  historyDialogVisible.value = true
  loadHistory()
}

const viewDetail = async (row: ApprovalInstance) => {
  try {
    const result: any = await getApprovalInstanceById({ id: row.id })
    console.log('详情API返回:', result)

    if (result.code === 200 && result.data) {
      currentInstance.value = result.data
      detailDialogVisible.value = true
    } else {
      console.log('详情API失败，使用行数据')
      // 使用当前行数据
      currentInstance.value = row
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取审批详情失败:', error)
    // 使用当前行数据
    currentInstance.value = row
    detailDialogVisible.value = true
  }
}

// 流程管理相关方法
const searchProcesses = async () => {
  processPagination.pageIndex = 1
  await loadProcesses()
}

const resetProcessSearch = () => {
  processSearchForm.processName = ''
  processSearchForm.formType = ''
  processSearchForm.isEnabled = undefined
  searchProcesses()
}

const showCreateProcessDialog = async () => {
  createProcessDialogVisible.value = true
  // 加载用户列表
  await loadUserList()
  resetCreateProcessForm()
}

const resetCreateProcessForm = () => {
  createProcessForm.processName = ''
  createProcessForm.formType = ''
  createProcessForm.description = ''
  createProcessForm.isEnabled = true
  createProcessForm.nodes = [
    {
      nodeName: '',
      approverName: '',
      orderIndex: 1,
      isRequired: true
    }
  ]
}

const addNode = () => {
  createProcessForm.nodes.push({
    nodeName: '',
    approverName: '',
    orderIndex: createProcessForm.nodes.length + 1,
    isRequired: true
  })
}

const removeNode = (index: number) => {
  if (createProcessForm.nodes.length > 1) {
    createProcessForm.nodes.splice(index, 1)
    // 重新排序
    createProcessForm.nodes.forEach((node, idx) => {
      node.orderIndex = idx + 1
    })
  }
}

const submitCreateProcess = async () => {
  try {
    await createProcessFormRef.value.validate()

    createProcessLoading.value = true

    const data = {
      processName: createProcessForm.processName,
      formType: createProcessForm.formType,
      description: createProcessForm.description,
      isEnabled: createProcessForm.isEnabled,
      createUserId: 1, // 当前用户ID，暂时固定
      nodes: createProcessForm.nodes.map(node => ({
        nodeName: node.nodeName,
        approverName: node.approverName,
        orderIndex: node.orderIndex,
        isRequired: node.isRequired
      }))
    }

    const result: any = await createApprovalProcess(data)
    if (result.code === 200) {
      ElMessage.success('创建审批流程成功')
      createProcessDialogVisible.value = false
      await loadProcesses()
      await loadStatistics() // 刷新统计数据
    } else {
      ElMessage.error(result.message || '创建失败')
    }
  } catch (error) {
    console.error('创建审批流程失败:', error)
    ElMessage.error('创建失败')
  } finally {
    createProcessLoading.value = false
  }
}

const loadProcesses = async () => {
  processLoading.value = true
  try {
    const params = {
      pageIndex: processPagination.pageIndex.toString(),
      pageSize: processPagination.pageSize.toString(),
      ...(processSearchForm.processName && { processName: processSearchForm.processName }),
      ...(processSearchForm.formType && { formType: processSearchForm.formType }),
      ...(processSearchForm.isEnabled !== undefined && { isEnabled: processSearchForm.isEnabled.toString() })
    }

    console.log('加载流程列表 - 请求参数:', params)
    const result: any = await getApprovalProcesses(params)
    console.log('加载流程列表 - API返回结果:', result)

    if (result.code === 200 && result.data) {
      processList.value = result.data.pageData || []
      processPagination.total = result.data.totalCount || 0
      console.log('加载流程列表 - 成功获取数据:', processList.value)
    } else {
      console.error('加载流程列表 - API返回错误:', result.message)
      ElMessage.error('获取流程列表失败')
      processList.value = []
      processPagination.total = 0
    }
  } catch (error) {
    console.error('获取流程列表失败:', error)
    ElMessage.error('获取流程列表失败')
    processList.value = []
    processPagination.total = 0
  } finally {
    processLoading.value = false
  }
}

const toggleProcessStatus = async (row: any) => {
  try {
    const result: any = await toggleApprovalProcess({ id: row.id })
    if (result.code === 200) {
      ElMessage.success('状态更新成功')
      await loadStatistics()
    } else {
      ElMessage.error('状态更新失败')
      row.isEnabled = !row.isEnabled // 恢复原状态
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败')
    row.isEnabled = !row.isEnabled // 恢复原状态
  }
}

const viewProcessNodes = async (row: any) => {
  try {
    console.log('查看节点 - 流程数据:', row)
    console.log('查看节点 - 流程ID:', row.id)

    // 获取流程详情和节点信息
    const result: any = await getApprovalProcessById({ id: row.id })
    console.log('查看节点 - API返回结果:', row.id)

    if (result.code === 200 && result.data) {
      currentProcess.value = result.data
      currentProcessNodes.value = result.data.nodes || []

      console.log('查看节点 - 节点数据:', currentProcessNodes.value)

      // 如果没有节点数据，显示提示
      if (!currentProcessNodes.value || currentProcessNodes.value.length === 0) {
        ElMessage.warning('该流程暂无审批节点，请先添加节点')
      }

      viewNodesDialogVisible.value = true
    } else {
      ElMessage.error('获取流程详情失败')
    }
  } catch (error) {
    console.error('获取流程详情失败:', error)
    ElMessage.error('获取流程详情失败')
  }
}

const editProcess = async (row: any) => {
  try {
    console.log('编辑流程 - 流程数据:', row)
    console.log('编辑流程 - 流程ID:', row.id)

    // 获取流程详情
    const result: any = await getApprovalProcessById({ id: row.id })
    console.log('编辑流程 - API返回结果:', result)

    if (result.code === 200 && result.data) {
      // 填充编辑表单
      editProcessForm.id = result.data.id
      editProcessForm.processName = result.data.processName
      editProcessForm.formType = result.data.formType
      editProcessForm.description = result.data.description || ''
      editProcessForm.isEnabled = result.data.isEnabled
      editProcessForm.nodes = result.data.nodes?.map((node: any) => ({
        nodeName: node.nodeName,
        approverName: node.approverName,
        orderIndex: node.orderIndex,
        isRequired: node.isRequired
      })) || []

      console.log('编辑流程 - 节点数据:', editProcessForm.nodes)

      // 如果没有节点数据，添加一个默认节点
      if (!editProcessForm.nodes || editProcessForm.nodes.length === 0) {
        editProcessForm.nodes = [
          {
            nodeName: '',
            approverName: '',
            orderIndex: 1,
            isRequired: true
          }
        ]
        ElMessage.info('该流程暂无审批节点，已为您添加一个默认节点')
      }

      // 加载用户列表
      await loadUserList()
      editProcessDialogVisible.value = true
    } else {
      ElMessage.error('获取流程详情失败')
    }
  } catch (error) {
    console.error('获取流程详情失败:', error)
    ElMessage.error('获取流程详情失败')
  }
}

const addEditNode = () => {
  editProcessForm.nodes.push({
    nodeName: '',
    approverName: '',
    orderIndex: editProcessForm.nodes.length + 1,
    isRequired: true
  })
}

const removeEditNode = (index: number) => {
  if (editProcessForm.nodes.length > 1) {
    editProcessForm.nodes.splice(index, 1)
    // 重新排序
    editProcessForm.nodes.forEach((node, idx) => {
      node.orderIndex = idx + 1
    })
  }
}

const submitEditProcess = async () => {
  try {
    await editProcessFormRef.value.validate()

    editProcessLoading.value = true

    const data = {
      id: editProcessForm.id,
      processName: editProcessForm.processName,
      formType: editProcessForm.formType,
      description: editProcessForm.description,
      isEnabled: editProcessForm.isEnabled,
      nodes: editProcessForm.nodes.map(node => ({
        nodeName: node.nodeName,
        approverName: node.approverName,
        orderIndex: node.orderIndex,
        isRequired: node.isRequired
      }))
    }

    const result: any = await updateApprovalProcess(data)
    if (result.code === 200) {
      ElMessage.success('更新审批流程成功')
      editProcessDialogVisible.value = false
      await loadProcesses()
      await loadStatistics() // 刷新统计数据
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('更新审批流程失败:', error)
    ElMessage.error('更新失败')
  } finally {
    editProcessLoading.value = false
  }
}

const deleteProcess = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除流程"${row.processName}"吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result: any = await deleteApprovalProcess({ id: row.id })
    if (result.code === 200) {
      ElMessage.success('删除成功')
      await loadProcesses()
      await loadStatistics()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 创建实例相关方法
const showCreateInstanceDialog = (row: any) => {
  createInstanceForm.approvalProcessId = row.id
  createInstanceForm.processName = row.processName
  createInstanceForm.businessType = row.formType
  createInstanceForm.businessName = ''
  createInstanceForm.businessId = ''
  createInstanceForm.content = ''
  createInstanceDialogVisible.value = true
}

const submitCreateInstance = async () => {
  try {
    await createInstanceFormRef.value.validate()

    createInstanceLoading.value = true

    const data = {
      approvalProcessId: createInstanceForm.approvalProcessId,
      businessType: createInstanceForm.businessType,
      businessName: createInstanceForm.businessName,
      businessId: createInstanceForm.businessId,
      content: createInstanceForm.content,
      initiatorId: 1, // 当前用户ID，暂时固定
      initiatorName: '系统用户' // 当前用户名，暂时固定
    }

    const result: any = await createApprovalInstance(data)
    if (result.code === 200) {
      ElMessage.success('创建审批实例成功')
      createInstanceDialogVisible.value = false
      // 刷新待办审批列表和统计数据
      await loadRecentApprovals()
      await loadStatistics()
    } else {
      ElMessage.error(result.message || '创建失败')
    }
  } catch (error) {
    console.error('创建审批实例失败:', error)
    ElMessage.error('创建失败')
  } finally {
    createInstanceLoading.value = false
  }
}

const handleProcessSizeChange = (size: number) => {
  processPagination.pageSize = size
  processPagination.pageIndex = 1
  loadProcesses()
}

const handleProcessCurrentChange = (page: number) => {
  processPagination.pageIndex = page
  loadProcesses()
}

// 待办审批相关方法
const searchTodos = async () => {
  todoPagination.pageIndex = 1
  await loadTodos()
}

const resetTodoSearch = () => {
  todoSearchForm.businessType = ''
  todoSearchForm.initiatorName = ''
  todoSearchForm.dateRange = []
  searchTodos()
}

const loadTodos = async () => {
  todoLoading.value = true
  try {
    // 直接调用获取用户待审批任务的API
    const result: any = await getMyPendingApprovals()
    console.log('API返回结果:', result) // 调试日志
    
    if (result.code === 200 && result.data) {
      console.log('API返回数据:', result.data) // 调试日志
      console.log('数据类型:', typeof result.data) // 调试日志
      console.log('是否为数组:', Array.isArray(result.data)) // 调试日志
      
      // 直接使用后端返回的待审批列表
      todoList.value = result.data || []
      todoPagination.total = todoList.value.length
      
      console.log('设置到todoList:', todoList.value) // 调试日志
    } else {
      console.log('API返回失败或数据为空:', result) // 调试日志
      todoList.value = getMockTodoData()
      todoPagination.total = todoList.value.length
    }
  } catch (error) {
    console.error('获取待办列表失败:', error)
    todoList.value = getMockTodoData()
    todoPagination.total = todoList.value.length
  } finally {
    todoLoading.value = false
  }
}

const viewTodoDetail = (row: ApprovalInstance) => {
  currentInstance.value = row
  detailDialogVisible.value = true
}

const approveTodo = async (row: ApprovalInstance) => {
  try {
    const result: any = await approveReject({
      instanceId: row.id,
      result: 'approve',
      comment: '同意'
    })
    if (result.code === 200) {
      ElMessage.success('审批成功')
      await loadTodos()
      await loadRecentApprovals() // 刷新最近审批列表
      await loadStatistics()
    } else {
      ElMessage.error('审批失败')
    }
  } catch (error) {
    console.error('审批失败:', error)
    ElMessage.error('审批失败')
  }
}

const rejectTodo = async (row: ApprovalInstance) => {
  try {
    const result: any = await approveReject({
      instanceId: row.id,
      result: 'reject',
      comment: '拒绝'
    })
    if (result.code === 200) {
      ElMessage.success('审批成功')
      await loadTodos()
      await loadRecentApprovals() // 刷新最近审批列表
      await loadStatistics()
    } else {
      ElMessage.error('审批失败')
    }
  } catch (error) {
    console.error('审批失败:', error)
    ElMessage.error('审批失败')
  }
}

const handleTodoSizeChange = (size: number) => {
  todoPagination.pageSize = size
  todoPagination.pageIndex = 1
  loadTodos()
}

const handleTodoCurrentChange = (page: number) => {
  todoPagination.pageIndex = page
  loadTodos()
}

// 审批历史相关方法
const searchHistory = async () => {
  historyPagination.pageIndex = 1
  await loadHistory()
}

const resetHistorySearch = () => {
  historySearchForm.businessType = ''
  historySearchForm.status = ''
  historySearchForm.dateRange = []
  searchHistory()
}

const loadHistory = async () => {
  historyLoading.value = true
  try {
    const params = {
      pageIndex: historyPagination.pageIndex.toString(),
      pageSize: historyPagination.pageSize.toString(),
      ...(historySearchForm.businessType && { businessType: historySearchForm.businessType }),
      ...(historySearchForm.status && { status: historySearchForm.status }),
      ...(historySearchForm.dateRange.length === 2 && {
        startDate: historySearchForm.dateRange[0],
        endDate: historySearchForm.dateRange[1]
      })
    }

    const result: any = await getApprovalInstances(params)
    if (result.code === 200 && result.data) {
      // 过滤已完成、已拒绝、已取消、审批中的审批
      const allData = result.data.pageData || []
      historyList.value = allData.filter((item: ApprovalInstance) =>
        ['approved', 'rejected', 'cancelled', 'completed', 'processing'].includes(item.status)
      )
      historyPagination.total = historyList.value.length
    } else {
      historyList.value = getMockHistoryData()
      historyPagination.total = historyList.value.length
    }
  } catch (error) {
    console.error('获取历史列表失败:', error)
    historyList.value = getMockHistoryData()
    historyPagination.total = historyList.value.length
  } finally {
    historyLoading.value = false
  }
}

const viewHistoryDetail = (row: ApprovalInstance) => {
  currentInstance.value = row
  detailDialogVisible.value = true
}

const handleHistorySizeChange = (size: number) => {
  historyPagination.pageSize = size
  historyPagination.pageIndex = 1
  loadHistory()
}

const handleHistoryCurrentChange = (page: number) => {
  historyPagination.pageIndex = page
  loadHistory()
}

// 模拟数据方法
const getMockProcessData = () => {
  return [
    {
      id: 1,
      processName: '采购申请流程',
      formType: '采购申请',
      description: '用于处理各类采购申请的审批流程',
      isEnabled: true,
      createTime: '2024-08-21T10:00:00'
    },
    {
      id: 2,
      processName: '请假申请流程',
      formType: '请假申请',
      description: '用于处理员工请假申请的审批流程',
      isEnabled: true,
      createTime: '2024-08-21T11:00:00'
    },
    {
      id: 3,
      processName: '报销申请流程',
      formType: '报销申请',
      description: '用于处理员工报销申请的审批流程',
      isEnabled: false,
      createTime: '2024-08-21T12:00:00'
    }
  ]
}

const getMockTodoData = () => {
  return recentApprovals.value.filter(item => item.status === 'pending')
}

const getMockHistoryData = () => {
  return recentApprovals.value.filter(item =>
    ['completed', 'rejected', 'cancelled'].includes(item.status)
  )
}

// 生命周期
onMounted(async () => {
  await loadStatistics()
  await loadRecentApprovals()
  await loadUserList() // 加载用户列表
})
</script>

<style scoped>
.approval-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.statistics {
  margin-bottom: 30px;
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.statistics-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.stat-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.recent-approvals {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recent-approvals h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.approval-detail {
  padding: 20px 0;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h4 {
  margin-bottom: 16px;
  color: #409eff;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.el-steps {
  margin-top: 16px;
}

.el-step__title {
  font-weight: bold;
}

.el-step__description {
  margin-top: 8px;
  color: #666;
}

/* 对话框内容样式 */
.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.approval-process-content,
.approval-todo-content,
.approval-history-content {
  padding: 0;
}

/* 表格操作按钮样式 */
.el-button+.el-button {
  margin-left: 8px;
}

/* 状态开关样式 */
.el-switch {
  margin: 0;
}
</style>
